import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '../request/token'
import store from '@/store'
import { ElMessage } from 'element-plus'
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    children:[
      {
        path: '/',
        name:'ArticleIndex',
        component: () => import('../views/Blog/BlogIndex.vue')
      }
      ,
      {
        path: '/article/:id',

        name:'ArticleDetail',
        component: () => import('../views/Blog/BlogView.vue')
      }
      ,
      {
        path: '/article/edit/:id',

        component: () => import('../views/Blog/BlogEdit.vue')
      },
      {
        path: '/article/create',

        component: () => import('../views/Blog/BlogCreate.vue')
      },
      {
        path: '/login',
        component:()=>import('../views/Login')
      }
    ]
  },

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


router.beforeEach((to, from, next) => {

  if (getToken()) {

    if (to.path === '/login') {
      next({path: '/'})
    } else {
      // console.log('全局路由守卫')
      // console.log(store.state.account)
      // console.log(store.state.account.length)
      if (store.state.account.length === 0) {
        store.dispatch('getUserInfo').then(data => { //获取用户信息
          next()
        }).catch(() => {
          ElMessage({
            type: 'warning',
            showClose: true,
            message: '登录已过期'
          })
          next({path: '/'})
        })
      } else {

        next()
      }
    }
  } else {
    if (to.matched.some(r => r.meta.requireLogin)) {
      ElMessage({
        type: 'warning',
        showClose: true,
        message: '请先登录哦'
      })

    }
    else {
      next();
    }
  }
})

export default router
